import { TableColumnObject } from 'amis/lib/renderers/Table'
import lodash from 'lodash'
import { ServiceSchema } from 'amis/lib/renderers/Service'

export type ServerColumnUtilsProps = TableColumnObject & {
	// id 关键字字段名
	valueField: string
	// 显示字段名
	labelField: string
	// 显示字段名2
	labelField2?: string
	// 格式化显示字段名
	labelFormatFn?: (item: any) => string
	// 限流获取对象方法
	getByIdsWithDebounce: <T>(id: string) => Promise<T[]>
}

class ServerColumnUtils {
	getSchema = (parmas: ServerColumnUtilsProps): TableColumnObject => {
		const name = parmas.name!
		const mergeSchema = Object.assign(
			{
				type: 'service',
				name: name,
				label: parmas.label,
				dataProvider: (data: any, setData: Function) => {
					const id = lodash.get(data, name)
					//console.log('ServerColumnUtils_dataProvider_id', id)
					parmas.getByIdsWithDebounce<any>(id).then(items => {
						let value = '-'
						lodash.forEach(items, item => {
							const itemId = lodash.get(item, parmas.valueField)
							if (itemId === id) {
								value = lodash.get(item, parmas.labelField)
								if (parmas.labelField2) {
									const value2 = lodash.get(item, parmas.labelField2)
									if (value2) {
										value = `${value}(${value2})`
									}
								}
								if (parmas.labelFormatFn) {
									value = parmas.labelFormatFn(item)
								}
							}
						})
						setData({ $label: value })
					})
				},
				body: {
					type: 'tpl',
					tpl: '${$label}',
				},
			} as ServiceSchema,
			parmas,
		)

		const schema = mergeSchema
		return schema as TableColumnObject
	}
}

export default new ServerColumnUtils()
